package cn.zmit.kuxi.widget;

import android.content.Context;
import android.util.AttributeSet;

import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrUIHandler;
import com.xdroid.widget.ptr.indicator.PtrIndicator;

/**
 * 下拉刷新头部
 * 
 * @author Robin time 2015-03-26 14:05:45
 * 
 */
public class PtrHeader extends PtrHeaderView implements PtrUIHandler {
	
	
	public PtrHeader(Context context) {
		super(context);
	}

	public PtrHeader(Context context, AttributeSet attrs) {
		super(context, attrs);
	}


	@Override
	public void onUIReset(PtrFrameLayout frame) {
	       if (getHeaderProgressBar().isSpinning()) { 
	    	   getHeaderProgressBar().stopSpinning();
	       }
	}

	@Override
	public void onUIRefreshPrepare(PtrFrameLayout frame) {
		statusPull(frame);
	}

	@Override
	public void onUIRefreshBegin(PtrFrameLayout frame) {
		setState(PtrHeaderView.STATE_REFRESHING);
	}

	@Override
	public void onUIRefreshComplete(PtrFrameLayout frame) {
		setState(PtrHeaderView.STATE_COMPLETE);
	}

	@Override
	public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch,
			byte status, PtrIndicator ptrIndicator) {
		
        final int mOffsetToRefresh = frame.getOffsetToRefresh();
        final int currentPos = ptrIndicator.getCurrentPosY();
        final int lastPos = ptrIndicator.getLastPosY();
        
        if (currentPos < mOffsetToRefresh && lastPos >= mOffsetToRefresh) {
            if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
            	statusPull(frame);
            }
        } else if (currentPos > mOffsetToRefresh && lastPos <= mOffsetToRefresh) {
            if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
            	statusRelease(frame);
            }
        }


		float percent = Math.min(1f, ptrIndicator.getCurrentPercent());
	    updateProgress( percent);

	}
	
	/**
	 * 显示释放刷新
	 * @param frame
	 */
	public void statusRelease(PtrFrameLayout frame){
        if (!frame.isPullToRefresh()) {
           setState(PtrHeaderView.STATE_READY);
        }
	}
	
	/**
	 * 显示下拉刷新
	 * @param frame
	 */
	public void statusPull(PtrFrameLayout frame){
        if (!frame.isPullToRefresh()) {
           setState(PtrHeaderView.STATE_NORMAL);
        }
	}
	
	/**
	 * 下拉过程中实时更新进度
	 * @param frame
	 * @param percent
	 */
	public void updateProgress(float percent){
        if (!getHeaderProgressBar().isSpinning()) { //如果不在旋转，更新进度
        	getHeaderProgressBar().setProgress(percent);
    		invalidate();
        }
	}

}
